package com.yanqu.road.server.manager.douluodalu.impl;

import com.yanqu.road.entity.activity.douluodalu.DouLuoDaLuUserEvent;
import com.yanqu.road.entity.activity.douluodalu.config.DouLuoDaLuEventInfo;
import com.yanqu.road.entity.activity.douluodalu.config.DouLuoDaLuRegionInfo;
import com.yanqu.road.entity.activity.douluodalu.data.DouLuoDaLuHelpRecordData;
import com.yanqu.road.entity.activity.douluodalu.data.DouLuoDaLuUserData;
import com.yanqu.road.entity.activity.douluodalu.enums.eDouLuoDaLuBuffType;
import com.yanqu.road.entity.activity.douluodalu.enums.eDouLuoDaLuEventType;
import com.yanqu.road.entity.enums.eChatContentType;
import com.yanqu.road.logic.activity.DouLuoDaLuLogic;
import com.yanqu.road.server.manager.douluodalu.CrossDouLuoDaLuContext;
import com.yanqu.road.server.manager.douluodalu.CrossDouLuoDaLuMgr;
import com.yanqu.road.server.manager.douluodalu.DouLuoDaLuEventResult;
import com.yanqu.road.server.manager.douluodalu.DouLuoEventHandleResult;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;

import java.util.ArrayList;
import java.util.List;

public class DouLuoDaLuBaseFightEventAction extends DouLuoDaLuBaseEventAction {


    public DouLuoDaLuBaseFightEventAction(CrossDouLuoDaLuContext context, DouLuoDaLuEventInfo eventInfo) {
        super(context, eventInfo);
    }

    @Override
    DouLuoDaLuEventResult init0() {
        return null;
    }

    @Override
    DouLuoEventHandleResult handle0(int action, byte[] params) {
        DouLuoEventHandleResult handleResult = new DouLuoEventHandleResult();
        if(action <= 0){
            handleResult.setRet(GameErrorCode.E_REQUEST_ARGUMENT_ERROR);
            return handleResult;
        }
        DouLuoDaLuUserEvent event = context.getUserData().getEvent();
        if(action == 1) {
            //攻击
            long now = DateHelper.getCurrentSecond();
            if(now - event.getAttackTime() < context.getActivity().getConfig().FOREST_ATTACK_CD){
                // 判断攻击时间
                handleResult.setRet(GameErrorCode.E_DOU_LUO_DA_LU_EVENT_ATTACK_CD);
                return handleResult;
            }
        }else if (action == 2) {
            //标记
            // 只有打了才能标记
            if (event.getStatus() == 0) {
                handleResult.setRet(GameErrorCode.E_DOU_LUO_DA_LU_MARK_AFTER_ATTACK);
                return handleResult;
            }
            if (event.getStatus() == 2) {
                // 不能重复标记
                handleResult.setRet(GameErrorCode.E_DOU_LUO_DA_LU_CANNOT_BE_REPEATED_MARK);
                return handleResult;
            }
            // 有可领取的协助奖励不能发起协助
            if (context.getActivity().hasReceiveHelpReward(context.getUserData())) {
                handleResult.setRet(GameErrorCode.E_DOU_LUO_DA_LU_HAVE_HELP_REWARD);
                return handleResult;
            }
        }else if(action == 3){
            //绕过
            if(event.getStatus() == 0){
                handleResult.setRet(GameErrorCode.E_DOU_LUO_DA_LU_EVENT_CANNOT_PASS);
                return handleResult;
            }
        }

        return handleResult;
    }

    /**
     * 新增标记记录
     */
    public DouLuoDaLuHelpRecordData buildHelpRecordData(DouLuoDaLuUserEvent event, int regionId, long totalBlood, long blood, long targetId, int eventTime){
        DouLuoDaLuHelpRecordData newMark = new DouLuoDaLuHelpRecordData(context.getActivity().maxHelpRecordId.incrementAndGet(),context.getActivity().getGroupId(), context.getActivityId());
        newMark.setEventId(event.getEventId());
        newMark.setRegionId(regionId);
        newMark.setTargetId(targetId);
        newMark.setTargetTotalBlood(totalBlood);
        newMark.setTargetBlood(blood);
        newMark.setUserId(context.getUserId());
        newMark.setInsertOption();
        newMark.setRecordTime(System.currentTimeMillis());
        newMark.setEventTIme(eventTime);
        context.getActivity().getHelpRecordDataList(context.getUserId(), true).add(newMark);

        return newMark;
    }

    /**
     * 处理攻击奖励
     */
    protected void dealAttackReward(DouLuoEventHandleResult handleResult, CrossDouLuoDaLuContext context, long totalBlood, Property hunHuan, Property goodsProperty) {
        List<Integer> buffIdList = new ArrayList<>();
//        synchronized (context.getUserData()) {
            if (handleResult.isKill()) {
                CrossDouLuoDaLuMgr.addHunHuanReward(hunHuan, context);
            }
            //仙草buff使用
            buffIdList.add(eDouLuoDaLuBuffType.DAMAGE_BUFF.getId());
            buffIdList.add(eDouLuoDaLuBuffType.SCORE_BUFF.getId());
            buffIdList.add(eDouLuoDaLuBuffType.GOODS_BUFF.getId());
            buffIdList = CrossDouLuoDaLuMgr.mergeXianCaoAndUse(context.getUserData(), buffIdList);
//        }

        DouLuoDaLuRegionInfo regionInfo = context.getActivity().getConfig().getRegionInfo(handleResult.getUserEvent().getRegionId());
        //积分奖励
        long addScore = CrossDouLuoDaLuMgr.calAddScore(handleResult.getDamage(), totalBlood, eventInfo, regionInfo);

        //积分加倍
        if(buffIdList.contains(eDouLuoDaLuBuffType.SCORE_BUFF.getId())){
            addScore = DouLuoDaLuLogic.calBuff(addScore, eDouLuoDaLuBuffType.SCORE_BUFF, context.getActivity().getConfig());
        }
        handleResult.setScore(addScore);

        //积分冲榜
        context.getUserData().setScore(addScore + context.getUserData().getScore());
        CrossDouLuoDaLuMgr.changeRank(context.getUserData());
        handleResult.setAllScore(context.getUserData().getScore());

        handleResult.setBuffIdList(buffIdList);
        //CrossDouLuoDaLuMgr.getLogger().debug("user {}, buffId {}", context.getUserId(), JSONObject.toJSONString(buffIdList));
        if(handleResult.isKill()){
            //魂环虽然是道具，但是不加到背包中，无意义
            handleResult.setHunHuan(PropertyHelper.parsePropertyToString(hunHuan));
            handleResult.setRewards(PropertyHelper.parsePropertyToString(goodsProperty));
        }
    }

    /**
     * 替换协助记录
     */
    protected void replaceHelpRecord(DouLuoDaLuUserData userData, DouLuoDaLuHelpRecordData oldMark, DouLuoDaLuHelpRecordData newMark) {
        userData.setCurrentHelpRecordData(newMark);

        StringBuilder contentBuilder = new StringBuilder();
        contentBuilder.append(newMark.getId()).append("|").append(newMark.getEventId()).append("|").append(newMark.getTargetId());
        if(eventInfo.getEventType() == eDouLuoDaLuEventType.PlayerEvent.getIntValue()){
            DouLuoDaLuUserData targetUser = context.getActivity().getAllUserMap().get(newMark.getTargetId());
            long serverId = targetUser.getServerId();
            String targetName = targetUser.getUserBaseInfo().getNickName();
            String decoration = targetUser.getUserBaseInfo().getDecoration();
            contentBuilder.append("|").append(serverId).append("|").append(targetName).append("|").append(decoration);
        }
        context.getActivity().addTeamChat(context.getTeamData(), userData,4, eChatContentType.Common.getContentType(), contentBuilder.toString(), System.currentTimeMillis() / 1000);

        if(oldMark != null){
//            synchronized (oldMark){
                if(oldMark.getKilledUserId() == 0){
                    CrossDouLuoDaLuMgr.updateHelpDataKillInfo(oldMark, -1, 0, userData);
                }
//            }
            DouLuoDaLuEventInfo oldEventInfo = context.getActivity().getEventInfo(oldMark.getEventId());
            if(oldEventInfo != null && oldEventInfo.getEventType() == eDouLuoDaLuEventType.PlayerEvent.getIntValue()){
                DouLuoDaLuUserData targetUser = context.getActivity().getAllUserMap().get(oldMark.getTargetId());
//                synchronized (targetUser) {
                    targetUser.getCanAttackUserSet().remove(context.getUserData());
//                }
            }
        }
    }
}
